package cn.itcast.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*@Order(-1)
@Component*/
public class AuthorizeFilter implements GlobalFilter {
    /**
     * 全局过滤方法
     *
     * @param exchange 请求上下文   包含:request  response
     * @param chain    过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        //获取请求参数 authorization 的值
        MultiValueMap<String, String> params = request.getQueryParams();
        String first = params.getFirst("authorization");
        //判读是否等于admin
        if ("admin".equals(first)) {
            //如果等于adminn  放行请求
            return chain.filter(exchange);
        }
        //如果不等于adminn  终止请求
        ServerHttpResponse response = exchange.getResponse();
        // 设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
